/**
 * 加减乘除丢失精度问题解决
 */

// 两个浮点数求和
export function accAdd(num1, num2) {
  var r1, r2, m
  try {
    r1 = num1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = num2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2))
  // return (num1*m+num2*m)/m;
  return Math.round(num1 * m + num2 * m) / m
}

// 两个浮点数相减
export function accSub(num1, num2) {
  var r1, r2, m, n
  try {
    r1 = num1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = num2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2))
  n = (r1 >= r2) ? r1 : r2
  return (Math.round(num1 * m - num2 * m) / m).toFixed(n)
}

// 两个浮点数相除
export function accDiv(num1, num2) {
  var t1, t2, r1, r2
  try {
    t1 = num1.toString().split('.')[1].length
  } catch (e) {
    t1 = 0
  }
  try {
    t2 = num2.toString().split('.')[1].length
  } catch (e) {
    t2 = 0
  }
  r1 = Number(num1.toString().replace('.', ''))
  r2 = Number(num2.toString().replace('.', ''))
  return (r1 / r2) * Math.pow(10, t2 - t1)
}

// 两个浮点数相乘
export function accMul(num1, num2) {
  var m = 0
  var s1 = num1.toString()
  var s2 = num2.toString()
  try {
    m += s1.split('.')[1].length
  } catch (e) {};
  try {
    m += s2.split('.')[1].length
  } catch (e) {};
  return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
}

// 四舍五入保留2位小数（若第二位小数为0，则保留一位小数）
export function keepTwoDecimal(num) {
  var result = parseFloat(num)
  if (isNaN(result)) {
    alert('传递参数错误，请检查！')
    return false
  }
  result = Math.round(num * 100) / 100
  return result
}

// 四舍五入保留2位小数（不够位数，则用0替补）
export function keepTwoDecimalFull(num) {
  var result = parseFloat(num)
  if (isNaN(result)) {
    alert('传递参数错误，请检查！')
    return false
  }
  result = Math.round(num * 100) / 100
  var s_x = result.toString()
  var pos_decimal = s_x.indexOf('.')
  if (pos_decimal < 0) {
    pos_decimal = s_x.length
    s_x += '.'
  }
  while (s_x.length <= pos_decimal + 2) {
    s_x += '0'
  }
  return s_x
}

// 千分位分隔符 （status是否万单位换算/保留num位小数，默认整数）
export function thousandDivision(number,status,num) {
  let text = ''
  if (status) {
  	// 万单位转换
  	if (number / 10000 > 1) {
  		number = (number / 10000).toFixed(2)
  		text = '万'
  	} else {
  		number = Number(number).toFixed(2)
  	}
  }

  number = parseInt(number)

  const numbers = number.toString().split('').reverse()
  const segs = []

  while (numbers.length) segs.push(numbers.splice(0, 3).join(''))


  return segs.join(',').split('').reverse().join('') + text
}

// 元/万元单位转换
export function unitConversion(num) {
  if (num / 10000 > 1) {
    return (num / 10000).toFixed(2) + '万'
  } else {
    return num.toFixed(2) + ''
  }
}

export default {
  accAdd,
  accSub,
  accDiv,
  accMul,
  keepTwoDecimal,
  keepTwoDecimalFull,
  thousandDivision,
  unitConversion
}
